<script setup lang="ts">
/**
 * @name RegionalEnergyStatistics
 * @description 区域能耗统计
 */
import {
  ENERGY_COMPREHENSIVE,
} from '../components'
import StatisticsPageWrapper from '../components/StatisticsPageWrapper/StatisticsPageWrapper.vue'
import type { Query } from '../components/type'
import { useQueryLists } from './index'

const [loading, setLoading] = useState(false)
const wrapperRef
  = ref<InstanceType<typeof StatisticsPageWrapper>>()
const {
  columns,
  tableData,
  x,
  y,
  l,
  pieData,
  cardData,
  emptyPie,
  getEnergyTypes,
  getEnergyData,
  getAllEnergyTypes,
} = useQueryLists()

async function queryChangeHandler(o: Query) {
  // console.log('query-change: ', o);
  const type = o.type
  const dataTime = o.time
  const energyId = o.energyType
    ? o.energyType === ENERGY_COMPREHENSIVE
      ? undefined
      : +o.energyType!
    : undefined
  // console.log('1 energyId: ', energyId)
  setLoading(true)
  try {
    await getAllEnergyTypes(dataTime)
    await getEnergyTypes({
      type,
      dataTime,
    })
    if (cardData.value.length === 0) {
      setLoading(false)
      return
    }

    // 确保选中第一个能源品种后再请求能源数据
    await nextTick()
    // console.log('2 energyId: ', o.energyType)
    await getEnergyData({
      type,
      dataTime,
      energyId: +o.energyType!,
    })
    setLoading(false)
  }
  catch (e) {
  }
  finally {
    setLoading(false)
  }
}

/** 切换能源卡片时只需要更新能耗数据 */
async function energyChangeHandler(o: Query) {
  if (cardData.value.length === 0)
    return
  // console.log('energy-change: ', o);
  const type = o.type
  const dataTime = o.time
  const energyId = o.energyType
    ? o.energyType === ENERGY_COMPREHENSIVE
      ? undefined
      : +o.energyType!
    : undefined
  try {
    setLoading(true)
    await getEnergyData({
      type,
      dataTime,
      energyId,
    })
    setLoading(false)
  }
  catch (e) {
  }
  finally {
    setLoading(false)
  }
}

/**
 * 没有用能单元的时候，需要手动触发query-change事件
 */
onMounted(async () => {
  const o = wrapperRef.value?.query!
  queryChangeHandler(o)
})
</script>

<template>
  <StatisticsPageWrapper
    ref="wrapperRef"
    :loading="loading"
    :show-point-tree="false"
    :tabs-props="{
      data: cardData,
    }"
    :bar-props="{ x, y, l, type: 'line' }"
    :pie-props="pieData"
    :table-props="{
      columns,
      data: tableData,
    }"
    :chart-height="240"
    :show-tips="true"
    :empty-pie="emptyPie"
    @query-change="o => queryChangeHandler(o)"
    @energy-change="o => energyChangeHandler(o)"
  />
</template>
